package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController{
    private Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/userlist.html")
    public String getUserList(Model model,
                              @RequestParam(value = "queryname",required = false) String queryUserName,
                              @RequestParam(value = "queryUserRole",required = false) String queryUserRole,
                              @RequestParam(value = "pageIndex",required = false) String pageIndex){
        logger.info("getUserList ---> queryUserName：" + queryUserName);
        logger.info("getUserList ---> queryUserRole：" + queryUserRole);
        logger.info("getUserList ---> pageIndex：" + pageIndex);

        int _queryUserRole = 0;
        List<User> userList = null;
        //设置页码容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if (queryUserName == null) {
            queryUserName = "";
        }
        if (queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //总数量
        int totalCount = userService.getUserCount();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        if(currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList",userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        model.addAttribute("queryUserName",queryUserName);
        model.addAttribute("queryUserRole",queryUserRole);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",currentPageNo);
        return "user/userlist";
    }

    /*@RequestMapping(value = "/useradd.html",method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user") User user){
        return "/user/useradd";
    }

    @RequestMapping(value = "/addsave.html",method = RequestMethod.POST)
    public String addUserAdd(User user, HttpSession session){
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if (userService.add(user)){
            return "redirect:/user/userlist.html";
        }
        return "useradd";
    }*/

    @RequestMapping(value = "/add.html",method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user") User user){
        return "user/useradd";
    }

    /*@RequestMapping(value = "/add.html",method = RequestMethod.POST)
    public String addSave(User user,HttpSession session,HttpServletRequest request,
                          @RequestParam(value ="attachs", required = false) MultipartFile[] attachs){
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
        logger.info("uploadFile path ============== > "+path);
        for(int i = 0;i < attachs.length ;i++){
            MultipartFile attach = attachs[i];
            if(!attach.isEmpty()){
                if(i == 0){
                    errorInfo = "uploadFileError";
                }else if(i == 1){
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("uploadFile oldFileName ============== > "+oldFileName);
                String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
                logger.debug(" prefix============> " + prefix);
                int files00ize = 500000;uploadFile
                logger.debug("uploadFile size============> " + attach.getSize());
                if(attach.getSize() >  filesize){//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if(i == 0){
                        idPicPath = path+File.separator+fileName;
                    }else if(i == 1){
                        workPicPath = path+File.separator+fileName;
                    }
                    logger.debug("idPicPath: " + idPicPath);
                    logger.debug("workPicPath: " + workPicPath);

                }else{
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
       if(flag){
            user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
            user.setCreationDate(new Date());
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);
            if(userService.add(user)){
                return "redirect:/user/userlist.html";
            }
        }
        return "useradd";
    }*/

    @RequestMapping(value = "/modify.html",method = RequestMethod.GET)
    public String getUserById(@RequestParam int uid,Model model){
        logger.debug("getUserId uid================" + uid);
        User user = userService.getUserById(uid);
        model.addAttribute(user);
        return "user/usermodify";
    }

    @RequestMapping(value = "/modifysave.html",method = RequestMethod.POST)
    public String modifyUserSave(User user, HttpSession session){
        logger.debug("modifyUserSave userid==================" + user.getId());
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if (userService.modify(user)){
            return "redirect:/user/userlist.html";
        }
        return "user/usermodify";
    }

   /* @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String view(@PathVariable int id, Model model){
        logger.debug("view id=============" + id);
        User user = userService.getUserById(id);
        model.addAttribute(user);
        return "user/userview";
    }*/

    @RequestMapping(value = "/view.html",method = RequestMethod.GET)\
    @ResponseBody
    public Object view(@RequestParam String id){
        logger.debug("view id：" + id);
        String cjson = "";
        if (null == id || "".equals(id)){
            return "nodata";
        } else {
            try {
                User user = userService.getUserById(Integer.valueOf(id));
                cjson = JSON.toJSONString(user);
                logger.debug("cjson：" + cjson);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                return "failed";
            }
        }
        return cjson;
    }

    //异步验证后台对比密码
    @RequestMapping(value="/chPwd",method=RequestMethod.GET)
    @ResponseBody
    public Object chPwd(@RequestParam String oldPassword,HttpSession session){
        logger.info("修改密码-->");
        logger.info("oldPassword ---->"+oldPassword);
        HashMap<String,Object> map = new HashMap<String, Object>();
        /*User user = ((User)session.getAttribute(Constants.USER_SESSION));
        if (oldPassword=="" || oldPassword==null){
            map.put("result","error");
        }else if (user==null){ //判断回话是否过期session.getAttribute(Constants.USER_SESSION)
            map.put("result","sessionerror");
        }else {
            int uid = ((User)session.getAttribute(Constants.USER_SESSION)).getId();
            logger.info("==登录id"+uid);
            user = userService.getUserById(uid);
            if (user.getUserPassword().equals(oldPassword)){
                map.put("result","true");
            }else {
                map.put("result","false");
            }
        }*/
        if (StringUtils.isNullOrEmpty(oldPassword)) {
            map.put("result", "error");
        } else {
            User user = (User) session.getAttribute(Constants.USER_SESSION);
            if (user == null) {
                map.put("result", "sessionerror");
            } else if (!user.getUserPassword().equals(oldPassword)) {
                map.put("result", "false");
            } else {
                map.put("result", "true");
            }
        }
        return JSONArray.toJSONString(map);
    }

    //修改密码
    @RequestMapping(value="/updatePwd")
    public String updatePwd(@RequestParam String newPassword,HttpSession session){
        logger.info("updatePwd-->");
        int uid = ((User)session.getAttribute(Constants.USER_SESSION)).getId();
        if (userService.updatePwd(uid,newPassword)>0){
            logger.info("updatePwd========修改密码成功");
            return "redirect:/login.html";
        }else {
            logger.info("updatePwd========修改密码失败");
            return "user/pwdmodify";
        }
    }

    //JSON获取集合
    @RequestMapping(value="/getRoleList",method=RequestMethod.GET)
    @ResponseBody
    public Object getRoleList(@RequestParam int uid,HttpSession session) {
        //List<Role> role
        return null;
    }

    //异步验证后台删除用户
    @RequestMapping(value="/delUser",method=RequestMethod.GET)
    @ResponseBody
    public Object delUser(@RequestParam int uid) {
        HashMap<String,Object> map = new HashMap<String, Object>();
        if (userService.deleteUserById(uid)>0){
            map.put("delResult","true");
        }else {
            map.put("delResult","false");
        }
        return JSONArray.toJSONString(map);
    }

}
